package per.qiao;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaFile;
import com.intellij.psi.PsiManager;

/**
 * Create by IntelliJ Idea 2018.2
 *
 * @author: qyp
 * Date: 2019-09-17 10:05
 */
public class DeprecatedClearAction extends AnAction {

    Project project;
    Editor editor;

    public DeprecatedClearAction() {
        setInjectedContext(true);
    }

    @Override
    public void update(AnActionEvent e) {
        final Presentation presentation = e.getPresentation();
        presentation.setEnabled(e.getProject() != null && e.getData(CommonDataKeys.EDITOR) != null
                && e.getData(CommonDataKeys.PSI_FILE) != null);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
        project = e.getProject();
        VirtualFile[] children = project.getBaseDir().getChildren();
        project = e.getRequiredData(CommonDataKeys.PROJECT);
        editor = e.getRequiredData(CommonDataKeys.EDITOR);
        loopChild(children, true);
    }

    private void loopChild(VirtualFile[] children, boolean isClear) {
        if (children == null || children.length <= 0) {
            return;
        }
        for (VirtualFile vfile : children) {
            // 直接跳过非java的单个文件
            if (!vfile.isDirectory() && !vfile.getName().contains(".java")) {
                return;
            }
            VirtualFile[] children1 = vfile.getChildren();
            // 遍历文件夹
            if (children1 != null && children1.length > 0) {
                loopChild(children1, isClear);
            } else {

                // 处理java文件
                PsiFile file1 = PsiManager.getInstance(project).findFile(vfile);
                CommandProcessor.getInstance().executeCommand(project, () -> {

                    try {
                        MultiHighlightHandler.invoke(project, editor, file1, isClear);
                    } catch (IndexNotReadyException ex) {
                        DumbService.getInstance(project)
                                .showDumbModeNotification("MultiHighlight requires indices "
                                        + "and cannot be performed until they are built");
                    }
                }, "MultiHighlight", null);
            }
        }
    }
}
